{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 总和最小的二叉树层级\n",
    "\n",
    "![Asked by Twitter](https://img.shields.io/badge/Asked%20by-Twitter-important?style=for-the-badge&logo=twitter)\n",
    "\n",
    "&emsp;&emsp;给定一棵二叉树，寻找总和最小的二叉树层级并返回总和值。对于下方的示例，树的总和为`10`，且`2 + 8 = 10`且`4 + 1 + 2 = 7`，所以应返回结果`7`：\n",
    "\n",
    "```text\n",
    "#     10\n",
    "#    /  \\\n",
    "#   2    8\n",
    "#  / \\    \\\n",
    "# 4   1    2\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Node:\n",
    "    def __init__(self, value, left=None, right=None):\n",
    "        self.value = value\n",
    "        self.left = left\n",
    "        self.right = right"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "def minimal_level_sum(node):\n",
    "    queue = [{'node': node, 'height': 1}]\n",
    "    levelSumMap = {}\n",
    "    while len(queue):\n",
    "        item = queue.pop(0)\n",
    "        currentNode = item['node']\n",
    "        currentHeight = item['height']\n",
    "        if currentHeight not in levelSumMap.keys():\n",
    "            levelSumMap[currentHeight] = currentNode.value\n",
    "        else:\n",
    "            levelSumMap[currentHeight] += currentNode.value\n",
    "        if currentNode.left:\n",
    "            queue.append({'node': currentNode.left, 'height': currentHeight + 1})\n",
    "        if currentNode.right:\n",
    "            queue.append({'node': currentNode.right, 'height': currentHeight + 1})\n",
    "    minimum = float('Inf')\n",
    "    for key in levelSumMap.keys():\n",
    "        minimum = min(minimum, levelSumMap[key])\n",
    "    return minimum"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "node = Node(10)\n",
    "node.left = Node(2)\n",
    "node.right = Node(8)\n",
    "node.left.left = Node(4)\n",
    "node.left.right = Node(1)\n",
    "node.right.right = Node(2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "7\n"
     ]
    }
   ],
   "source": [
    "print(minimal_level_sum(node))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
